#!/bin/sh
#
#  CHECK_UPDATE -- Check to see if an update is available.  Return $status=1
#  if a patch is available.
#

set -e

# Initialize the $iraf and environment.
if [ -z "$iraf" ]; then
  if [ -e "$HOME/.iraf/setup.sh" ]; then
    . "$HOME/.iraf/setup.sh"
  else
    . unix/hlib/setup.sh
  fi
else
    . "$iraf/unix/hlib/setup.sh"
fi


# Called from Makefile, set iraf root.
. "$iraf/unix/hlib/irafuser.sh"


# Check to see if a patch file is available.

rm -f /tmp/_rdate /tmp/_pdate

FGET="${iraf}util/fget"
${FGET} -q -o /tmp/_rdate http://iraf.noao.edu/ftp/v216/PCIX/.release_date || true
${FGET} -q -o /tmp/_pdate http://iraf.noao.edu/ftp/v216/PCIX/.patch_release || true

if [ -e /tmp/_rdate ]; then
    rdate=$(cat /tmp/_rdate)
else
    echo "cannot get rdate"
    exit 0
fi
if [ -e /tmp/_pdate ]; then
    pdate=$(cat /tmp/_pdate)
else
    echo "cannot get pdate"
    exit 0
fi


if [ -e "${iraf}/.patch_release" ]; then
    ipdate=$(ls -l --time-style=+%s ${iraf}/.patch_release | awk '{ print ($6) }')
else
    ipdate=0
fi

if [ "$1" = "-d" ]; then			# Debug
  echo " rdate = $rdate"
  echo " pdate = $pdate"
  echo "ipdate = $ipdate"
fi

if [ "$rdate" -gt "$pdate" ]; then			# New Release
    exit 1
fi


if [ "$pdate" = 0 ]; then
    exit 0				
elif [ "$pdate" -gt "$ipdate" ] && [ "$ipdate" != 0 ]; then	# Patch newer than installed
    exit 1
fi

exit 0						# No update available
